package com.mstanford.movie.controller;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.mstanford.movie.utils.DataUtil;

public class SingleLoginListener implements HttpSessionListener, HttpSessionAttributeListener {

	public void sessionCreated(HttpSessionEvent event) {}

	@SuppressWarnings("unchecked")
	public void sessionDestroyed(HttpSessionEvent event) {

		HttpSession session = event.getSession();
		Object obj = session.getAttribute("member");
		
		if(!DataUtil.isEmpty(obj)) {
			Map<String, String> map = (Map<String, String>)obj;
			String memberEmail = map.get("memberEmail");
			
			if(!DataUtil.isEmpty(memberEmail)) {
				ServletContext context = session.getServletContext();
				context.removeAttribute(memberEmail);
			}
		}
		
		System.out.println("................session destroy................");
	}

	@SuppressWarnings("unchecked")
	public void attributeAdded(HttpSessionBindingEvent event) {

		Object obj = event.getSession().getAttribute("member");
		
		if(!DataUtil.isEmpty(obj)) {
			Map<String, String> map = (Map<String, String>)obj;
			String memberEmail = map.get("memberEmail");
			
			if(!DataUtil.isEmpty(memberEmail)) {
				ServletContext context = event.getSession().getServletContext();
				context.setAttribute(memberEmail, memberEmail);
			}
		}
		
		System.out.println("................ attribute add................");
	}

	public void attributeRemoved(HttpSessionBindingEvent event) {}

	public void attributeReplaced(HttpSessionBindingEvent event) {}
}